package com.example.myinventory.ui.item

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myinventory.data.ItemRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn

class ItemDetailsViewModel(
    savedStateHandle: SavedStateHandle,
    private val itemRepository: ItemRepository
) : ViewModel() {
    private val itemId: Int = checkNotNull(savedStateHandle[ItemDetailsDestination.itemIdArg])
    val uiState: StateFlow<ItemDetailsUiState> =
        itemRepository.getItemStream(itemId)
            .filterNotNull()
            .map { ItemDetailsUiState(it.toItemDetails()) }
            .stateIn(
                scope = viewModelScope,
                started = SharingStarted.WhileSubscribed(TIMEOUT_MILLIS),
                initialValue = ItemDetailsUiState()
            )

    companion object {
        private const val TIMEOUT_MILLIS = 5_000L
    }

    suspend fun reduceQuantityByOne() {
        val currentItem = uiState.value.itemDetails.toItem()
        if (currentItem.quantity > 0) {
            itemRepository.updateItem(currentItem.copy(quantity = currentItem.quantity - 1))
        }
    }

    suspend fun delete() {
        itemRepository.deleteItem(uiState.value.itemDetails.toItem())
    }
}

data class ItemDetailsUiState(
    val itemDetails: ItemDetails = ItemDetails()
)
